package com.dyit.service.impl;

import com.dyit.config.RabbitMqConfig;
import com.dyit.dao.IAdminDao;
import com.dyit.dao.IBookDao;
import com.dyit.entity.Admin;
import com.dyit.entity.Book;
import com.dyit.exception.Book.BookAlreadyExistsException;
import com.dyit.exception.user.AccountBlankException;
import com.dyit.exception.user.AccountNotExistException;
import com.dyit.exception.user.PasswordBlankException;
import com.dyit.exception.user.PasswordIncorrectException;
import com.dyit.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AdminServiceImpl implements IAdminService {
    /**
     *  ---------------------------------login
     */
    @Autowired
    private IAdminDao iad;
    @Autowired
    private IBookDao iBookDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public Admin login(String account, String password) {
        if(account==null||"".equals(account)){
            throw new AccountBlankException("你没有输入账号！");
        }
        if(password==null||"".equals(password)){
            throw new PasswordBlankException("你没有输入密码！！");
        }

        //根据账号先找
        Admin admin = iad.findAdminByAccount(account);
        if(admin==null){
            throw new AccountNotExistException("此管理员账号不存在！");
        }
        //输入账号密码了根据账号密码一起找
        Admin admin1 = iad.findAdminByAccountAndPassword(account,password);
        if(admin1==null){
            throw new PasswordIncorrectException("你的账户名或密码不正确！");
        }
        return admin1;
    }

    /**
     * -----------------------------------save book
     * @param book
     * @return
     * 往rabbitmq里加书
     */
    @Override
    public void addBook(Book book) {
        if (iBookDao.findBookByTitle(book.getTitle())!=null){
            throw new BookAlreadyExistsException("此书已经存在！请换个书名试试！");
        }
        rabbitTemplate.convertAndSend(RabbitMqConfig.DIRECT_EXCHANGE,RabbitMqConfig.ROUTING_KEY,book);
        log.info("【生产者】向mq发送book对象："+book);
    }
}
